package cn.th.service.impl;

import cn.th.dto.AdDto;
import cn.th.entity.AdvLabel;
import cn.th.entity.Advertising;
import cn.th.mapper.AdvertisingMapper;
import cn.th.service.IAdvLabelService;
import cn.th.service.IAdvertisingService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 广告表 服务实现类
 * </p>
 *
 * @author cn.th
 * @since 2024-03-30
 */
@Service
public class AdvertisingServiceImpl extends ServiceImpl<AdvertisingMapper, Advertising> implements IAdvertisingService {

    @Autowired
    private IAdvLabelService advLabelService;

    @Autowired
    private IAdvertisingService advertisingService;

    /**
     * 查询广告
     * @param page 页面
     * @param limit 每页的数据
     * @param keywordCount 关键词等级
     * @param title 标题
     * @param type 类型
     * @param sort 排序
     * @return 返回
     */
    @Override
    public Map<String,Object> queryAd(int page, int limit, String keywordCount, String title, String type, String sort, String publishName, Integer status) {
        LambdaQueryWrapper<Advertising> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(title), Advertising::getTitle, title);
        wrapper.eq(StringUtils.hasLength(type), Advertising::getType, type);
        wrapper.eq(StringUtils.hasLength(publishName), Advertising::getPublishName, publishName);
        wrapper.eq(StringUtils.hasLength(keywordCount),Advertising::getLevel,keywordCount);
        wrapper.eq(status!=null && status>-1 && status<6, Advertising::getStatus,status);
        if (sort != null && sort != "")
        {
            if (sort.equals("-id"))
                wrapper.orderByDesc(Advertising::getId);
            if (sort.equals("%2Bid"))
                wrapper.orderByAsc(Advertising::getId);
        }

        Page<Advertising> page1 = new Page<>(page,limit);
        Page<AdDto> adDtoPage = new Page<>();

        advertisingService.page(page1,wrapper);

        //对象拷贝
        BeanUtils.copyProperties(page1,adDtoPage,"records");

        List<Advertising> records = page1.getRecords();

        List<AdDto> list = records.stream().map((item) -> {
            AdDto adDto = new AdDto();

            BeanUtils.copyProperties(item,adDto);

            //当前广告的id
            Long adId = item.getId();//分类id

            LambdaQueryWrapper<AdvLabel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AdvLabel::getAdId,adId);

            List<AdvLabel> advLabelList = advLabelService.list(lambdaQueryWrapper);
            adDto.setAdvLabels(advLabelList);
            return adDto;
        }).collect(Collectors.toList());

        adDtoPage.setRecords(list);

        Map<String, Object> data = new HashMap<>();
        data.put("total",adDtoPage.getTotal());
        data.put("rows",adDtoPage.getRecords());

        return data;
    }

    /**
     * 回显广告
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> queryById(Long id) {
        LambdaQueryWrapper<Advertising> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Advertising::getId,id);


        Map<String, Object> data = new HashMap<>();
        return data;
    }

    /**
     * 新增广告 要么全成功，要么全失败
     * @param adDto
     */
    @Transactional
    public void saveAd(AdDto adDto) {
        //保存广告的基本信息到广告表advertising
        this.save(adDto);

        Long adId = adDto.getId();//广告id

        //标签
        List<AdvLabel> advLabelList = adDto.getAdvLabels();
        advLabelList = advLabelList.stream().map((item) -> {
            item.setAdId(adId);
            return item;
        }).collect(Collectors.toList());

        //保存标签数据到标签表adv_label
        advLabelService.saveBatch(advLabelList);
    }

    /**
     * 更新广告
     * @param adDto
     */
    @Transactional
    public void updateWithId(AdDto adDto) {
        //更新广告表基本信息
        this.updateById(adDto);

        //清理当前广告对应标签---adv_label表的delete操作
        LambdaQueryWrapper<AdvLabel> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AdvLabel::getAdId,adDto.getId());
        advLabelService.remove(queryWrapper);

        //添加当前提交过来标签数据---adv_label表的insert操作
        List<AdvLabel> advLabelList = adDto.getAdvLabels();

        advLabelList = advLabelList.stream().map((item) -> {
            item.setAdId(adDto.getId());
            return item;
        }).collect(Collectors.toList());

        advLabelService.saveBatch(advLabelList);
    }

    /**
     * 修改广告时页面的数据展示
     * @param id
     * @return
     */
    @Override
    @Transactional
    public AdDto getAdDtoById(Long id) {
        //查询广告基本信息，从Advertising表查询
        Advertising advertising = this.getById(id);

        AdDto adDto = new AdDto();
        BeanUtils.copyProperties(advertising,adDto);

        //查询当前菜品对应的口味信息，从adv_label表查询
        LambdaQueryWrapper<AdvLabel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdvLabel::getAdId,advertising.getId());
        List<AdvLabel> advLabelList = advLabelService.list(queryWrapper);
        adDto.setAdvLabels(advLabelList);

        return adDto;
    }


}
